package com.sunny.myproject.produce.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sunny.myproject.buy.entity.BuyPlan;
import com.sunny.myproject.buy.service.BuyPlanService;
import com.sunny.myproject.core.base.action.BaseAction;
import com.sunny.myproject.core.base.util.CommonUtil;
import com.sunny.myproject.core.base.util.LoginUtil;
import com.sunny.myproject.produce.entity.Bom_sub;
import com.sunny.myproject.produce.entity.Mrp;
import com.sunny.myproject.produce.entity.Mrp_sub;
import com.sunny.myproject.produce.service.MrpService;
import com.sunny.myproject.produce.service.Mrp_subService;
import com.sunny.myproject.storem.entity.Materiel;
import com.sunny.myproject.storem.entity.Warehouse;
import com.sunny.myproject.storem.entity.Warehouse_temp;
import com.sunny.myproject.storem.service.Warehouse_tempService;

@Controller
@RequestMapping("/produce/mrp")
public class MrpAction extends BaseAction<Mrp>{

	private String title = "MRP";
	private String action = "produce/mrp";
	private String function = "mrp";
	

	private Logger logger = Logger.getLogger(MrpAction.class);
	
	@Autowired
	private MrpService service;
	
	@Autowired
	private Mrp_subService mrp_subService;
	
	@Autowired
	private Warehouse_tempService warehouse_tempService;
	
	@Autowired
	private BuyPlanService buyPlanService;
	
	@Override
	@RequestMapping(params="list")
	public String list(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			super.pager = super.pageStart(model, request, response, action, function, title);
			super.pager = super.pageEnd(model, service.num(criterions), pager);
			super.returnValue(model, service.find(criterions, pager));
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/mrpList";
	}

	@Override
	@RequestMapping(params="add")
	public String add(HttpServletRequest request, HttpServletResponse response) {
		logger.info("mrp add");
		super.add(title, request);
		return "produce/mrpEdit";
	}

	@Override
	@RequestMapping(params="edit")
	public String edit(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			Mrp mrp = service.findById(super.edit(title, model, request));
			
			//如果mrp 为已审批的,不能修改
			if(mrp.getStatus()!=null&&mrp.getStatus().equalsIgnoreCase("已审核"))
			LoginUtil.error_forward(response, request, "已审核，不能修改", "produce/mrp?list");
			
			super.returnValue(model, mrp);
			
			@SuppressWarnings("unchecked")
			List<Mrp_sub> mrp_subs = (List<Mrp_sub>) service.queryHql("select sb from Mrp_sub sb where sb.mrp.id="+mrp.getId());
			logger.info("mrp_subs size:"+mrp_subs.size());
			model.addAttribute("mrp_subs", mrp_subs);
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/mrpEdit";
	}

	@Override
	@RequestMapping(params="delete")
	public String delete(HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("mrp delete");
		try {
			Long[] ids = super.param2(request);
			String idsS = "";
			for (Long long1 : ids) {
				idsS = long1+",";
			}
			//删除mrp下的mrp_sub
			service.queryBulkUpdate("delete Mrp_sub ms where ms.mrp.id in ("+CommonUtil.subString_1(idsS)+")");
			
			service.deleteByIds(super.param2(request));
		} catch (Exception e) {
			logger.error(e);
		}
		return "redirect:/produce/mrp?list";
	}

	@Override
	@RequestMapping(params="save")
	public String save(HttpServletRequest request,
			HttpServletResponse response, Mrp t) {
		try {
			Long id = t.getId();
			service.save(t);
			if (id == null) {
				logger.info("t.id 为null");
				// 当t.id 为空的时候,只保存bom中的bom_sub materiel
				// for mrp_sub materiel
				@SuppressWarnings("unchecked")
				List<Materiel> materiels = (List<Materiel>) service.queryHql("select bs.materiel from Bom_sub bs where bs.bom.id="
								+ t.getBom().getId());
				for (Materiel materiel : materiels) {
					logger.info("mrp_sub save");
					Mrp_sub mrp_sub = new Mrp_sub();
					mrp_sub.setMateriel(materiel);
					mrp_sub.setMrp(t);
					mrp_subService.save(mrp_sub);
				}
			} else {
				logger.info("t.id 不为null");
				// mrp_sub
				String[] mrp_sub_id = request.getParameterValues("mrp_sub_id");
				String[] mrp_sub_materielId = request.getParameterValues("mrp_sub_materielId");
				String[] mrp_sub_amount = request.getParameterValues("mrp_sub_amount");
				String[] mrp_sub_loss = request.getParameterValues("mrp_sub_loss");
				String[] mrp_sub_remark = request.getParameterValues("mrp_sub_remark");
				
				String[] mrp_sub_code = request.getParameterValues("mrp_sub_code");

				for (int i = 0; i < mrp_sub_remark.length; i++) {
					Mrp_sub mrp_sub = new Mrp_sub();
					if (mrp_sub_id != null) {
						mrp_sub.setId(Long.parseLong(mrp_sub_id[i]));
					}
					// materiel of mrp_sub
					Materiel materiel = new Materiel();
					materiel.setId(Long.parseLong(mrp_sub_materielId[i]));
					mrp_sub.setMateriel(materiel);

					mrp_sub.setAmount(Double.parseDouble(mrp_sub_amount[i]));
					mrp_sub.setLoss(Double.parseDouble(mrp_sub_loss[i]));
					mrp_sub.setRemark(mrp_sub_remark[i]);
					mrp_sub.setCode(mrp_sub_code[i]);
					mrp_sub.setMrp(t);

					 mrp_subService.save(mrp_sub);
				}

			}
		} catch (Exception e) {
			logger.error(e);
		}
		return "redirect:/produce/mrp?list";
	}

	@Override
	@RequestMapping(params="view")
	public String view(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			super.returnViewValue(model, service.findById(super.view(title, model, request)));
		} catch (Exception e) {
			logger.error(e);
		}
		return "produce/mrpEdit";
	}
	
	
	/**
	 * mrp操作是查询仓库中是否有足够的物料生产产品
	 * 如果不够的话,就生产采购订单
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params="mrp")
	public String mrp(Model model,HttpServletRequest request,
			HttpServletResponse response){
		logger.info("mrp 运算");
		Long[] ids = super.param2(request);
		for (Long long1 : ids) {
			Mrp mrp = service.findById(long1);
			//如果已MRP,则直接调转到列表页面
			if(mrp.getStatus().equals("已MRP"))
				LoginUtil.error_forward(response, request, "已MRP,不能再MRP", "produce/mrp?list");
			//bom_subs
			@SuppressWarnings("unchecked")
			List<Bom_sub> bom_subs = (List<Bom_sub>) service
					.queryHql("select bs from Bom_sub bs where bs.bom.id="
							+ mrp.getBom().getId());
			String materielIds = "";
			for (Bom_sub bom_sub : bom_subs) {
				materielIds = bom_sub.getMateriel().getId()+",";
			}
			
			//stores
			@SuppressWarnings("unchecked")
			List<Warehouse> warehouses = (List<Warehouse>) service
					.queryHql("select wh from Warehouse wh where wh.materiel.id in("
							+ CommonUtil.subString_1(materielIds) + ")");
			
			for(Bom_sub bom_sub:bom_subs){
				for(Warehouse warehouse:warehouses){
					if(warehouse.getMateriel().equals(bom_sub.getAmount())){
						//查询store_temp 中存在materiel 数量,先不考虑
						@SuppressWarnings("unchecked")
						List<Warehouse_temp> warehouse_temps = (List<Warehouse_temp>) service.queryHql("select wht from Warehouse_temp wht where wht.materiel.id="+bom_sub.getMateriel().getId());
						//在warehouse_temp中存在materiel,则仓库中已经存在待采购
						if(warehouse_temps.size()>0){
							saveWarehouse_temp(bom_sub.getAmount(),bom_sub.getMateriel(),mrp,"unfinished");
						}else{
							//当待生产的数量大于仓库中存在的数量
							//则要保存到warehouse_temp中
							if(warehouse.getNowStock()<bom_sub.getAmount()){
								//得到相差的数量 
								double amount = bom_sub.getAmount()-warehouse.getNowStock();

								saveWarehouse_temp(amount,bom_sub.getMateriel(),mrp,"finished");
							}
						}
					}
				}
			}
			mrp.setStatus("已MRP");
			service.save(mrp);
		}
		return "redirect:/produce/mrp?list";
	}

	/**
	 * 保存saveWarehouse_temp
	 * @param amount
	 * @param materiel
	 * @param mrp
	 */
	private void saveWarehouse_temp(double amount, Materiel materiel, Mrp mrp,String status) {
		Warehouse_temp warehouse_temp = new Warehouse_temp();
		warehouse_temp.setAmount(amount);
		warehouse_temp.setMateriel(materiel);
		warehouse_temp.setMrp(mrp);
		warehouse_temp.setStatus(status);
		
		warehouse_tempService.save(warehouse_temp);
		
		//创建采购计划
		BuyPlan buyPlan = new BuyPlan();
		buyPlan.setBuy_from("mrp");
		buyPlan.setMrp(mrp);
		buyPlan.setAmount(amount);
		buyPlanService.save(buyPlan);
	}

	@RequestMapping(params="approval")
	public String approval(Model model,HttpServletRequest request,
			HttpServletResponse response){
		logger.info("mrp approval");
		Mrp mrp = service.findById(super.edit(title, model, request));
		mrp.setStatus("已审核");
		service.save(mrp);
		return "redirect:/produce/mrp?list";
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册定义的属性编辑器
		//1.日期
		 DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		 CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		 //表示如果命令对象有date类型的属性,将使用该属性编辑器进行类型转换
		 binder.registerCustomEditor(Date.class, dateEditor);
	}
	
}
